package com.kxn.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

import com.kxn.entity.Book;
import com.kxn.entity.Spitter;
import com.kxn.exception.MyExcept;

@WebService(targetNamespace="http://192.168.1.6")
public class LibraryServiceImpl {
	private static List<Book> list = new ArrayList<Book>();
	private static int currentId = 0;
	
	public LibraryServiceImpl(){
		
	}
	
	@WebMethod
	@WebResult(name="id")
	public int addRawBook(@WebParam(name="name") String name,@WebParam(name="author") String author){
		Book book = new Book();
		book.setId(++currentId);
		book.setName(name);
		book.setAuthor(author);
		list.add(book);
		System.out.println(currentId);
		return currentId;
	}
	
	@WebMethod
    @WebResult(name="rawBook")
    public String getRawBook(@WebParam(name="id") int id) {
        Book goal=null;
        for(Book b: list) {
            if (id == b.getId()) {
                goal = b; 
                break;
            }
        }
        StringBuilder result = new StringBuilder();
        if (goal == null) {
            result.append("No Book Found");
        } else {
            result.append("[id=").append(goal.getId()).append(";name=").append(goal.getName()).append(";author=").append(goal.getAuthor());
        }
        return result.toString();
    }
    
    @WebMethod
    public void deleteBook(@WebParam(name="id") int id) throws MyExcept {
        Book goal=null;
        for(Book b: list) {
            if (id == b.getId()) {
                goal = b; 
                break;
            }
        }
        if(goal == null) {
            throw new MyExcept("Fail to delete", "Id not exist.");
        } else {
            list.remove(goal);
        }
    }
}
